import React, { useState, useEffect, useRef } from 'react';
import io from 'socket.io-client';
import {BASE_URL,flask_url} from "../config";

import axios from 'axios';
import {
  Box, Container, CssBaseline, Divider, List, ListItem, ListItemText,
  Paper, Tab, Tabs, Typography, Avatar, TextField, IconButton
} from '@mui/material';
import SendIcon from '@mui/icons-material/Send';
import DeleteIcon from '@mui/icons-material/Delete';
import Navbar from '../components/Navbar';
import { Link, useLocation } from 'react-router-dom';
import { getMessages, deleteMessages } from '../api/chat';
import { v4 as uuidv4 } from 'uuid';
import { navigationItems } from '../App';

// 临时注释掉WebSocket连接，防止错误
const socket = io(flask_url); // 根据后端地址修改
// 创建一个模拟的socket对象，防止代码报错
// const socket = {
//   on: () => {},
//   off: () => {},
//   emit: () => {},
//   id: 'mock-socket-id'
// };

const Message = () => {
  const location = useLocation();
  const passedUser = location.state?.user;
  const [contacts, setContacts] = useState([]);
  const [selectedUser, setSelectedUser] = useState(null);
  const [inputText, setInputText] = useState('');
  const [chats, setChats] = useState({});
  const currentUserId = Number(localStorage.getItem("id"));
  const messagesEndRef = useRef(null);

  useEffect(() => {
    if (passedUser) {
      setContacts(prev => {
        if (!prev.find(c => c.id === passedUser.id)) {
          return [...prev, passedUser];
        }
        return prev;
      });
      setSelectedUser(passedUser.id);
    }
  }, [passedUser]);

  useEffect(() => {
    getMessages(currentUserId).then(res => {
      const data = res || {};
      setChats(data);

      const newContacts = Object.keys(data).map(id => {
        const messages = data[id];
        const latestMessage = messages[messages.length - 1];
        const name = latestMessage?.sender_id === currentUserId ? latestMessage.receiver_name : latestMessage.sender_name;
        const avatar = latestMessage?.sender_id === currentUserId ? latestMessage.receiver_avatar : latestMessage.sender_avatar;
        return { id: Number(id), name, avatar };
      });

      setContacts(prev => {
        const merged = [...prev];
        newContacts.forEach(nc => {
          if (!merged.find(c => c.id === nc.id)) {
            merged.push(nc);
          }
        });
        return merged;
      });

      if (selectedUser === null && newContacts.length > 0) {
        setSelectedUser(newContacts[0].id);
      }
    });
  }, []);

  useEffect(() => {
    socket.on('receive_message', (msg) => {
      const { sender_id, receiver_id } = msg;
      const chatPartnerId = sender_id === currentUserId ? receiver_id : sender_id;
       if (sender_id !== currentUserId && receiver_id !== currentUserId) {
    return; // 不处理，直接跳过
  }
      setChats(prev => {
        const updatedChats = { ...prev };
        const messages = updatedChats[chatPartnerId] || [];
        if (!messages.find(m => m.id === msg.id)) {
          messages.push(msg);
          updatedChats[chatPartnerId] = messages;
        }
        return updatedChats;
      });

      setContacts(prev => {
        if (!prev.find(c => c.id === chatPartnerId)) {
          const name = msg.sender_id === currentUserId ? msg.receiver_name : msg.sender_name;
          const avatar = msg.sender_id === currentUserId ? msg.receiver_avatar : msg.sender_avatar;
          return [...prev, { id: chatPartnerId, name, avatar }];
        }
        return prev;
      });
    });

    return () => {
      socket.off('receive_message');
    };
  }, []);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [chats, selectedUser]);

  const handleSend = () => {
    if (inputText.trim() && selectedUser !== null) {
      const message = {
        id: uuidv4(),
        sender_id: currentUserId,
        receiver_id: selectedUser,
        content: inputText
      };
      socket.emit('send_message', message);
      setInputText('');
    }
  };

  const handleDeleteChat = (contactId) => {
    deleteMessages(currentUserId, contactId).then(() => {
      setChats(prev => {
        const updatedChats = { ...prev };
        delete updatedChats[contactId];
        return updatedChats;
      });
      setContacts(prev => prev.filter(c => c.id !== contactId));
      if (selectedUser === contactId) {
        setSelectedUser(null);
      }
    });
  };

  return (
    <div className="message-page">
      <CssBaseline />
      <Navbar />
      <Container
              maxWidth="false"
              sx={{
                backdropFilter: 'blur(4px)',
                backgroundColor: 'rgba(255,255,255,0.6)',
                borderRadius: 3,
                p: 2,
                mt: 3,
              }}
            >
      
            <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
              <Tabs
                  value={location.pathname}
                  indicatorColor="secondary"
                  textColor="secondary"
                  variant="scrollable"
                  scrollButtons="auto"
                  sx={{
                    borderBottom: '2px solid #f3e5f5',
                    mb: 2,
                    '& .MuiTab-root': {
                      transition: 'all 0.3s ease-in-out',
                    },
                    '& .Mui-selected': {
                      color: '#8e24aa',
                      fontWeight: 'bold',
                    },
                    '& .MuiTabs-indicator': {
                      height: 3,
                      backgroundColor: '#ce93d8',
                      borderRadius: 2,
                    }
                  }}
                >
      
                {navigationItems.map((item) => (
                  <Tab
                    key={item.path}
                    label={item.label}
                    value={item.path}
                    component={Link}
                    to={item.path}
                    sx={{
                      minWidth: 100,
                      borderRadius: 2,
                      mx: 0.5,
                      transition: 'all 0.3s',
                      color: '#8e24aa',
                      '&:hover': {
                        backgroundColor: '#ffe0f0',
                        color: '#d81b60',
                      },
                      '&.Mui-selected': {
                        fontWeight: 'bold',
                        color: '#d81b60',
                        backgroundColor: '#fff0f5',
                      },
                    }}
                  />
                ))}
              </Tabs>
              </Box>
            </Container>
<Container maxWidth="lg" sx={{ mt: 3, mb: 3 }}>
  <Paper 
    elevation={6} 
    sx={{ 
      display: 'flex', 
      height: '75vh', 
      borderRadius: 4, 
      overflow: 'hidden', 
      boxShadow: '0 10px 30px rgb(0 0 0 / 0.12)' 
    }}
  >
    {/* 联系人列表 */}
    <Box 
      sx={{ 
        width: 300, 
        borderRight: '1px solid #e0e0e0', 
        bgcolor: '#f5f7fa', 
        display: 'flex', 
        flexDirection: 'column' 
      }}
    >
      <Typography 
        variant="h6" 
        sx={{ 
          p: 3, 
          fontWeight: '700', 
          color: '#1976d2', 
          letterSpacing: 0.5 
        }}
      >
        消息列表
      </Typography>
      <Divider />
      <List sx={{ flexGrow: 1, overflowY: 'auto' }}>
        {contacts.map(contact => (
          <ListItem
            key={contact.id}
            button
            selected={selectedUser === contact.id}
            onClick={() => setSelectedUser(contact.id)}
            sx={{
              mb: 1,
              borderRadius: 2,
              px: 2,
              py: 1.25,
              transition: 'background-color 0.25s, box-shadow 0.25s',
              bgcolor: selectedUser === contact.id ? '#e3f2fd' : 'transparent',
              boxShadow: selectedUser === contact.id ? '0 2px 12px rgb(25 118 210 / 0.15)' : 'none',
              '&:hover': {
                bgcolor: selectedUser === contact.id ? '#bbdefb' : '#e8f0fe',
                boxShadow: selectedUser === contact.id ? '0 4px 14px rgb(25 118 210 / 0.2)' : '0 1px 4px rgb(0 0 0 / 0.05)',
              },
              display: 'flex',
              alignItems: 'center',
              position: 'relative',
            }}
          >
            <Avatar 
              src={contact.avatar} 
              sx={{ width: 44, height: 44, mr: 2, boxShadow: '0 1px 4px rgb(0 0 0 / 0.1)' }} 
            />
            <ListItemText
              primary={
                <Typography 
                  sx={{ 
                    fontWeight: selectedUser === contact.id ? 700 : 500, 
                    color: '#0d47a1', 
                    fontSize: '1rem',
                    whiteSpace: 'nowrap',
                    textOverflow: 'ellipsis',
                    overflow: 'hidden',
                  }}
                >
                  {contact.name}
                </Typography>
              }
            />
            <IconButton
              edge="end"
              size="small"
              onClick={(e) => {
                e.stopPropagation();
                handleDeleteChat(contact.id);
              }}
              sx={{
                opacity: 0,
                position: 'absolute',
                right: 8,
                top: '50%',
                transform: 'translateY(-50%)',
                transition: 'opacity 0.3s',
                '&:hover': {
                  color: '#d32f2f',
                },
              }}
              className="delete-btn"
              aria-label="删除聊天"
            >
              <DeleteIcon fontSize="small" />
            </IconButton>
          </ListItem>
        ))}
      </List>
    </Box>

    {/* 聊天区域 */}
    <Box 
      sx={{ 
        flex: 1, 
        display: 'flex', 
        flexDirection: 'column', 
        bgcolor: '#fff',
        position: 'relative',
      }}
    >
      {/* 选中用户提示 */}
      {!selectedUser && (
        <Box
          sx={{
            flexGrow: 1,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            color: '#90a4ae',
            fontSize: '1.1rem',
            fontWeight: 500,
            userSelect: 'none',
          }}
        >
          请选择联系人开始聊天
        </Box>
      )}

      {/* 聊天消息区 */}
      {selectedUser && (
        <Box sx={{ flex: 1, overflowY: 'auto', p: 3, scrollbarWidth: 'thin', bgcolor: '#f5f5f5',scrollbarColor: '#90caf9 transparent' }}>
          {(chats[selectedUser] || []).map((msg, index) => {
            const isMe = msg.sender_id === currentUserId;
            return (
              <Box
                key={index}
                sx={{
                  display: 'flex',
                  width: '100%',
                  mb: 2,
                  justifyContent: isMe ? 'flex-end' : 'flex-start',
                  alignItems: 'flex-end',
                  gap: 1.5,
                }}
              >
                {/* 对方头像 */}
                {!isMe && (
                  <Avatar
                    src={msg.sender_avatar}
                    sx={{ width: 36, height: 36, boxShadow: '0 1px 4px rgb(0 0 0 / 0.1)' }}
                  />
                )}

                {/* 消息气泡 */}
<Box
  sx={{
    maxWidth: '40vw',
    px: 3,
    py: 1.5,
    bgcolor: isMe ? '#1976d2' : '#fff',        // 蓝色 / 白色
    color: isMe ? '#fff' : '#000',             // 白字 / 黑字
    borderRadius: '24px',                      // 更圆润的气泡
    boxShadow: '0 2px 8px rgb(0 0 0 / 0.1)',
    fontSize: '1rem',
    fontWeight: 500,
    whiteSpace: 'pre-wrap',
    overflowWrap: 'break-word',
    wordBreak: 'break-word',
    position: 'relative',
  }}
>


                  {msg.content}
                  <Typography
  variant="caption"
  sx={{
    display: 'block',
    mt: 0.8,
    fontSize: '0.7rem',
    color: isMe ? 'rgba(255,255,255,0.7)' : '#999',
    textAlign: 'right',
    userSelect: 'none',
  }}
>

                    {new Date(new Date(msg.timestamp).getTime() + 8 * 60 * 60 * 1000).toLocaleString()}
                  </Typography>
                </Box>

                {/* 自己头像 */}
                {isMe && (
                  <Avatar
                    src={msg.sender_avatar}
                    sx={{ width: 36, height: 36, boxShadow: '0 1px 4px rgb(0 0 0 / 0.1)' }}
                  />
                )}
              </Box>
            );
          })}
          <div ref={messagesEndRef} />
          {(chats[selectedUser]?.length ?? 0) === 0 && (
            <Typography
              color="text.secondary"
              sx={{ textAlign: 'center', mt: 4, fontSize: '1rem', userSelect: 'none' }}
            >
              暂无聊天记录
            </Typography>
          )}
        </Box>
      )}

      <Divider />

      {/* 输入框区域 */}
      {selectedUser && (
        <Box
          sx={{
            display: 'flex',
            p: 2,
            bgcolor: '#f9fbfe',
            borderTop: '1px solid #e3e9f3',
          }}
        >
          <TextField
            fullWidth
            variant="outlined"
            size="medium"
            placeholder="输入消息..."
            value={inputText}
            onChange={(e) => setInputText(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleSend()}
            sx={{
              bgcolor: '#fff',
              borderRadius: 3,
              '& .MuiOutlinedInput-root': {
                '& fieldset': {
                  borderColor: '#90caf9',
                },
                '&:hover fieldset': {
                  borderColor: '#42a5f5',
                },
                '&.Mui-focused fieldset': {
                  borderColor: '#1565c0',
                  boxShadow: '0 0 6px rgb(21 101 192 / 0.5)',
                },
                paddingRight: 1,
              },
              input: {
                fontSize: '1rem',
                padding: '10.5px 14px',
              },
            }}
            autoFocus
          />
          <IconButton
            color="primary"
            onClick={handleSend}
            sx={{
              ml: 2,
              bgcolor: '#1976d2',
              '&:hover': {
                bgcolor: '#1565c0',
                boxShadow: '0 4px 14px rgb(21 101 192 / 0.8)',
              },
              width: 48,
              height: 48,
              borderRadius: 3,
            }}
            aria-label="发送消息"
          >
            <SendIcon />
          </IconButton>
        </Box>
      )}
    </Box>
  </Paper>

  {/* 全局CSS提升删除按钮显示 */}
  <style>{`
    .MuiListItem-root:hover .delete-btn {
      opacity: 1 !important;
    }
  `}</style>
</Container>



    </div>
  );
};

export default Message;
